<template>
  <div>
    <el-button type="primary" @click="showAdd = true">添加用户</el-button>
    <el-table :data="userList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="showAdd" title="添加用户">
      <el-form :model="form">
        <el-form-item label="用户名"><el-input v-model="form.username"/></el-form-item>
        <el-form-item label="手机号"><el-input v-model="form.phone"/></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="form.email"/></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getUserListApi, addUserApi, updateUserApi, deleteUserApi } from '../api/user'
const userList = ref([])
const showAdd = ref(false)
const form = ref({})
const loadUsers = async () => { userList.value = await getUserListApi() }
const saveUser = async () => {
  if(form.value.id) await updateUserApi(form.value)
  else await addUserApi(form.value)
  showAdd.value = false
  loadUsers()
}
const editUser = (row) => { form.value = { ...row }; showAdd.value = true }
const deleteUser = async (id) => { await deleteUserApi(id); loadUsers() }
onMounted(loadUsers)
</script> 